const chalk = require('chalk')
const ora = require('ora')
const fsextra = require('fs-extra')
const path = require('path')
const download = require('download-git-repo')
const gitRepo = 'https://gitee.com:hong1993/vuepress-template#master'

function downloadTpl(downloadPath,templatePath) {
    return new Promise(function(resolve, reject) {
        const downloadSpinner = ora(chalk.cyan('Downloading template...'))
		const templateVersion = path.resolve(__dirname,'../template/package')
        const creatorVersion = require('../package.json')
        downloadSpinner.start()

        download(gitRepo, downloadPath,{ clone: true },err => {
            if (err) {
                downloadSpinner.text = chalk.red('Download template failed.')
                downloadSpinner.fail()
                fsextra.remove(templatePath, err => {
                    if (err) {
                        return console.error(err)   
                    } else {
                        console.log(`${chalk.yellow('WARNING:')}TEMPLATE folder has been revoked.`)
                    }
                  })
                return reject(err)
            } else {
                downloadSpinner.text = 'Download template successful.'
                downloadSpinner.succeed()
                let _ver = require(templateVersion).version
                let _creator = require(templateVersion).creator.substring(2)
                console.log(chalk.yellow('Template version: ' + _ver))
                resolve()
            }

        })

    })
}
module.exports = downloadTpl